package com.xxx.system.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.system.domain.Permission;
import com.xxx.system.query.PermissionQuery;
import com.xxx.system.service.impl.PermissionServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/perm")
@Api(tags = "权限接口类")
public class PermissionController {

    @Autowired
    private PermissionServiceImpl permissionService;


    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个权限")
    public R<Permission> findOne(@PathVariable("id") Long id) {
        Permission permission = permissionService.findOne(id);
        return R.ok(permission);
    }

    @PutMapping
    @ApiOperation(value = "新增or修改权限")
    public R<Void> addOrUpdate(@RequestBody Permission permission) {
        permissionService.updatePermission(permission);
        return R.ok();
        //try {
        //    //获取请求参数的id
        //    Long id = permission.getId();
        //    if (id == null) {//新增没有传递id
        //        permissionService.addPermission(permission);
        //    } else {
        //        permissionService.updatePermission(permission);
        //    }
        //} catch (Exception e) {
        //    e.printStackTrace();
        //    return R.fail("网络异常，请稍后重试!");
        //}
        //return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除单个权限")
    public R<Void> deleteById(@PathVariable("id") Long id) {
        try {
            permissionService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("网络异常，请稍后重试!");
        }
        return R.ok();
    }


    @GetMapping()
    @ApiOperation(value = "查询所有权限")
    public R<List<Permission>> findAllPerm() {
        List<Permission> perms = permissionService.findAllPerm();
        return R.ok(perms);
    }

    @PostMapping
    @ApiOperation(value = "高级查询&分页")
    public R<PageInfo<Permission>> queryPage(@RequestBody PermissionQuery permissionQuery) {
        List<Permission> PermissionList = permissionService.queryPage(permissionQuery);
        //返回的是封装好的分页(总数,list)
        return R.ok(new PageInfo<Permission>(PermissionList));
    }

    @PatchMapping
    @ApiOperation(value = "批量删除")
    public R<Void> deletePermissionByIds(@RequestBody Long[] ids) {
        try {
            permissionService.deletePermissionByIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            //返回的json格式  {"success":false,"message":"错误信息"}
            return R.fail("网络异常，请稍后重试!");
        }
        return R.ok();
    }
}